# -*- coding: utf-8 -*-
# 通过小蜜蜂平台 对比监控中没有加入的集群名标签
import time,pymysql
import requests,json
import logging
from aws_requests_auth.aws_auth import AWSRequestsAuth
rebot="https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=5ec72ac5-fa5d-4454-83dc6ba5e5"
auth = AWSRequestsAuth(aws_access_key='fEPub6H7tlxkFj31',
                       aws_secret_access_key='EZQGsId5OyoLtcjgaqzVMxYeiTPkBmF0',
                       aws_host='bee-backend.baozun.com',
                       aws_region='cn-shanghai',
                       aws_service='bee')
#存放结果数据
Bin_Go = []
#存放写库数据
Store_robot=[]
def test():
    url = 'https://bee-backend.baozun.com/api/v1/container/cluster/'
    params = {
       #'code': '1542p7m',
        ' page':'1',
         'page_size': '2'
    }
    r = requests.get(url=url, params=params,auth=auth).json()
    x = r['data']['total']  #获取总条数

    params["page_size"] = str(x)  #单次获取所以条数
    r = requests.get(url,params,auth=auth).json()
    x = r['data']['list']
    #thenos 生产--测试集群名合并
    app = thanos_sit() + thanos_prod()
    for i in range(len(x)):
        #平台集群标识符没有在thenos的集群名
        if x[i]["identity"] not in app:
            bbi = (x[i]["identity"],x[i]["name"],"集群名没有在thos的标签")
            Store_robot.append(bbi)
            Bin_Go.append(bbi)#追加到列表，调用写库批量写入
            print(bbi)


#thanos-prod 关联的集群标签
def thanos_prod():
    thanos_prod_result = []
    url = 'http://thanos-query.cloud.bz/api/v1/query?'
    params = {
        'query': 'sum by (k8s_cluster)(max_container_cpu_usage_per)'
    }

    u = requests.get(url=url,params=params).json()
    rose = u['data']['result']
    for j in rose:
        resules = j["metric"]["k8s_cluster"]  #集群名
        thanos_prod_result.append(resules)  #k8s_cluster 集群标签追加到列表
    print(len(thanos_prod_result))
    print("返回thanos-prod 生产")
    return thanos_prod_result

#thanos-sit 集群标签
def thanos_sit():
    thanos_sit_result = []
    url = 'http://thanos-query-sit.cloud.bz/api/v1/query?'
   # url = 'http://thanos-query-sit.cloud.bz/graph?g0.range_input=1h&g0.max_source_resolution=0s&g0.expr=sum%20by%20(k8s_cluster)(max_container_cpu_usage_per)%20%20%3E%2060&g0.tab=1'
    params = {
        'query': 'sum by (k8s_cluster)(max_container_cpu_usage_per)',
        # 'dedup': 'true',
        # 'partial_response': 'true'

    }
    u = requests.get(url,params).json()
    rose = u['data']['result']
    for j in rose:
        resules = j["metric"]["k8s_cluster"]  #集群名
        thanos_sit_result.append(resules)
    print("返回thanos-sit 测试")
    print(len(thanos_sit_result))
    return thanos_sit_result


class Project_Robot():
    url = 'https://bee-backend.baozun.com/resource_management/op_project_api/'
    params = {
        'page': '1',
        'size': '1',
        'data': '{"active":1}'
    }

    Store_robot = []
    # 分页次数
    def subtraction(self,x, y):
        if x < y:
            return y - x  # 将被减数看作0，返回减数的正数值
        else:
            return y

    def project_robot(self):
        # 单页输出条数
        sums = 10
        # 初始分页号
        num = 0
        # 状态
        status = True
        q_map = {}

        r = requests.get(url=self.url, params=self.params, auth=auth)
        print(r)
        counts = json.loads(r.text)['data']['count']  # 获取数据总条数
        print(counts)
        while status:  # 无限循环状态
            # print("当前页数",num + 1)
            counts = self.subtraction(sums, counts)  # 返回总条数数据 - 单次输出数据
            if counts > sums:
                self.params['page'] = num = num + 1  # 定义页号
                self.params['size'] = sums  # 单次获取数据条数
            else:
                self.params['page'] = num = num + 1  # 定义页号
                self.params['size'] = counts  # 不足单次输出数据时执行
                status = False  # 状态重新赋值r
            r = requests.get(url=self.url, params=self.params, auth=auth)
            x = json.loads(r.text)['data']['data']
            for j in x:

                ProjectGroup = j["ProjectGroup"]  # 项目名
                comment = j["comment"]  # 项目描述
                ProjectGroup_en = j["ProjectGroup_en"]  # 项目
                non_prod_robot = j["non_prod_robot"]  # 非生产机器人
                robot = j['robot']  # 生产机器人
                project_tag = j["project_tag"]  # 项目标签
                if not robot:  # 生产机器人为空
                    robots = {"项目名": ProjectGroup,
                              "项目描述": comment,
                              "项目标识符": ProjectGroup_en,
                              "非生产机器人": non_prod_robot,
                              "生产机器人": robot,
                              "项目标签": project_tag}

                    # print(robots['项目标识符'])
                    self.app_node(robots)
                    self.application_home(robots)

    # 应用服务
    def application_home(self,*args):
        urls = 'https://bee-backend.baozun.com/resource_management/application_home_api/'
        paramsa = {
            'code': '33j8yvg',
            'page': '1',
            'data': '{"ProjectGroup":"nike-e-invoice"}'
        }

        ProjectGroup_en = args[0]['项目标识符']
        # json 方式转成（序列化）字典进行修改
        u = json.loads(paramsa['data'])  #
        # 修改字典中volume
        u['ProjectGroup'] = ProjectGroup_en
        paramsa['data'] = "{}".format(u)  # 转字符串传入
        r = requests.get(url=urls, params=paramsa, auth=auth)
        x = json.loads(r.text)['data']['data']
        for g in x:
            if g['allnode']:

                if args[0]['项目标识符'] in AllOw:  # 白名单
                    pass
                elif args[0]['项目标签']:  # 品牌名值不为空执行
                    Store_robot.append(
                        (args[0]['项目标识符'], args[0]['项目标签'], "来自应用服务robot未添加机器人地址"))
                else:
                    Store_robot.append((args[0]['项目标识符'], args[0]['项目标识符'], "来自应用服务robot未添加机器人地址"))

                return

    # 应用节点
    def app_node(self,*args):
        url = ' https://bee-backend.baozun.com/resource_management/nodemanage_api/'

        params = {
            'code': '33j8w9t',
            'page': '1',
            'size': '1',
            'data': '{"ProjectGroup":"tic-pms","Env":"prod"}'
        }
        ProjectGroup_en = args[0]['项目标识符']
        # json 方式转成（序列化）字典进行修改
        u = json.loads(params['data'])  #
        # 修改字典中volume
        u['ProjectGroup'] = ProjectGroup_en
        params['data'] = "{}".format(u)  # 转字符串传入
        r = requests.get(url=url, params=params, auth=auth)
        x = json.loads(r.text)['data']['count']
        if x:
            # print("来自应用节点")
            if args[0]['项目标识符'] in AllOw:
                pass
            elif args[0]['项目标签']:
                Store_robot.append((args[0]['项目标识符'], args[0]['项目标签'], "来自应用节点robot未添加机器人地址"))
            else:
                Store_robot.append((args[0]['项目标识符'], args[0]['项目标识符'], "来自应用节点robot未添加机器人地址"))
        else:
            self.container_node(args[0])

    # 容器节点
    def container_node(self,*args):
        url = 'https://bee-backend.baozun.com/api/v1/app/k8s/node/'

        params = {
            'code': '33j8w9t',
            ' page_size': '10',
            'ProjectGroup': 'activity',
            'Env': 'prod'
        }
        ProjectGroup_en = args[0]['项目标识符']
        params['ProjectGroup'] = ProjectGroup_en
        r = requests.get(url=url, params=params, auth=auth)
        x = json.loads(r.text)['data']['total']
        if x:
            # print("来自容器节点")
            if args[0]['项目标识符'] in AllOw: #白名单不匹配里面的值
                pass
            elif args[0]['项目标签']:
                Store_robot.append((args[0]['项目标识符'], args[0]['项目标签'], "来自容器节点robot未添加机器人地址"))
            else:
                Store_robot.append((args[0]['项目标识符'], args[0]['项目标识符'], "来自容器节点robot未添加机器人地址"))

    # 写入操作
    def PyMysql(self):
        # 打开数据库连接
        db = pymysql.connect(host='w-bzrds-g4qk894976813f33d11.service.testdb',
                             user='sftp_user',
                             password='c(5ph5lJ1taKMy0#f',
                             database='test',
                             charset='utf8')
        with db.cursor() as cursor:
            sql = 'insert into test.cluser_labels (' \
                  '`project`,' \
                  '`database_src`,' \
                  '`annotation`) values (%s,%s,%s)'
            paramse = Store_robot
            cursor.executemany(sql, paramse)
            time.sleep(2)

            # 关闭句柄
            cursor.close()
            db.commit()
            db.close()
            print("写入完成")

    # 机器人推送
    def send_alertmsg(self,p, voice):
        def webhook():
            # send_uat_url='https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=daaa8310-e94e-49f5-8fdd-650d68559703'
            text = '> <font color=\"warning\">{0}:</font>:{1}\n'.format(p, len(voice))

            for i in voice:
                # text += '> <font color="red">\n</font>'
                text += '> <font color="red">应用:{0}----标签:{1}\n</font>'.format(i[0], i[1])

            sendlist = "<@jm006190><@jm019440><@jm030390>"
            text = text + sendlist
            send_values = {
                "msgtype": "markdown",
                "markdown": {
                    "content": text
                }
            }
            headers = {'Content-Type': 'application/json'}
            data = json.dumps(send_values)
            repose = requests.post(rebot, data, headers=headers)
            print(repose.status_code)
        #条件判断
        if len(voice):
            webhook()
        else:
            logging.info("结果为空 不行推送")

# 白名单
AllOw = ['fulljet', 'bbywecom',
         'bidata', 'terminus',
         'ddc-unified', 'gucci-cloud',
         'converse-onesystem',
         'rsc-automation', 'dss',
         'performance-team',
         'knife',
         'komodo'
         ]



#入口
if __name__ == '__main__':
    LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
    logging.basicConfig(  # filename='D:/JetBrains/JetBrains/实验\python/临时-练习/my.log',
        level=logging.DEBUG,
        format=LOG_FORMAT
        )
    #实例化
    my_Robot = Project_Robot()
    my_Robot.project_robot()
    my_Robot.send_alertmsg("当前未配置机器人的项目",Store_robot)
    #thanos_sit()
    test()
    #触发机器人推送
    my_Robot.send_alertmsg("当前未配置监控的cluster集群",Bin_Go)
    #写库
    #my_Robot.PyMysql()

